<?php

namespace app\common\model;

use think\Model;
use think\Exception;
use think\Loader;
use think\Lang;
use think\Hook;
use think\Request;
use app\common\model\CapitalDetails;
use app\common\traits\model\TraitModel;

/**
 * 会员资金模型
 */
class Capitals extends Model
{
    protected $table         = 'deposit';
    protected $resultSetType = 'collection';

    use TraitModel;

    public function users()
    {
        return $this->belongsTo('app\common\model\Users', 'user_id');
    }

    public function getCapital($user_id = null)
    {
        if ($user_id || Request::instance()->user) {
            $user_id = $user_id ? : Request::instance()->user->id;
        }else {
            throw new Exception("Parameter error", 20002);
        }

        $user_capital = $this->where(['user_id' => $user_id])->column('amount', 'types');
        
        if (!$user_capital) {
            $this->createCapital(['user_id' => $user_id, 'amount' => 0, 'types' => 'integral']);
            $this->createCapital(['user_id' => $user_id, 'amount' => 0, 'types' => 'blance']);
            $user_capital = ['integral' => 0, 'blance' => 0];
        }
        return $user_capital;
    }

    public function getBlance($user_id = null)
    {
        $user_capital = $this->getCapital($user_id);
        return $user_capital['blance'];
    }

    public function getIntegral($user_id = null)
    {
        $user_capital = $this->getCapital($user_id);
        return $user_capital['integral'];
    }

    public function createCapital($user_capital_info)
    {
        return $this->create($user_capital_info, true);
    }

    public function blance($amount = null)
    {
        $this->_type = 'blance';
        if ($amount) {
            $this->_amount = $amount;
        }
        return $this;
    }

    public function integral($amount = null)
    {
        $this->_type = 'integral';
        if ($amount) {
            $this->_amount = $amount;
        }
        return $this;
    }

    public function amount($amount)
    {
        $this->_amount = $amount;
        return $this;
    }

    public function inc($option = [])
    {
        $option = array_merge(['type' => Lang::get('income'), 'remark' => Lang::get('income')], $option);
        $this->capitalOperation(Request::instance()->user->id, $this->_type, $this->_amount, $option);
    }

    public function dec($abs = true, $option = [])
    {
        $option = array_merge(['type' => Lang::get('consumption'), 'remark' => Lang::get('consumption')], $option);
        $this->capitalOperation(Request::instance()->user->id, $this->_type, (0 - abs($this->_amount)), $option, $abs);
    }

    /**
     * 增加余额
     * @param  [type] $amount  [description]
     * @param  [type] $user_id [description]
     * @param  array  $option  [description]
     * @return [type]          [description]
     */
    public function incBlance($amount, $user_id, $option = [])
    {
        $option = array_merge(['type' => Lang::get('income'), 'remark' => Lang::get('income')], $option);
        $this->capitalOperation($user_id, 'blance', $amount, $option);
    }
    /**
     * 减少余额
     * @param  [type] $amount  [description]
     * @param  [type] $user_id [description]
     * @param  array  $option  [description]
     * @return [type]          [description]
     */
    public function reduceBlance($amount, $user_id, $option = [], $abs = true)
    {
        $option = array_merge(['type' => Lang::get('consumption'), 'remark' => Lang::get('consumption')], $option);
        $this->capitalOperation($user_id, 'blance', (0 - abs($amount)), $option, $abs);
    }

    /**
     * 增加积分
     * @param  [type] $amount  [description]
     * @param  [type] $user_id [description]
     * @param  array  $option  [description]
     * @return [type]          [description]
     */
    public function incIntegral($amount, $user_id, $option = [])
    {
        $option = array_merge(['type' => Lang::get('income'), 'remark' => Lang::get('income')], $option);
        $this->capitalOperation($user_id, 'integral', $amount, $option);
    }
    /**
     * 减少积分
     * @param  [type] $amount  [description]
     * @param  [type] $user_id [description]
     * @param  array  $option  [description]
     * @return [type]          [description]
     */
    public function reduceIntegral($amount, $user_id, $option = [], $abs = true)
    {
        $option = array_merge(['type' => Lang::get('consumption'), 'remark' => Lang::get('consumption')], $option);
        $this->capitalOperation($user_id, 'integral', (0 - abs($amount)), $option, $abs);
    }
    
    /**
     * 资金操作
     * @param  [type]  $user_id [description]
     * @param  [type]  $type    [description]
     * @param  [type]  $amount  [description]
     * @param  array   $option  [description]
     * @param  boolean $abs     [description]
     * @return [type]           [description]
     */
    protected function capitalOperation($user_id, $type, $amount, $option = [], $abs = true)
    {
        if ($amount == 0) {
            return ;
        }
        
        $user_capital = $this->getCapital($user_id);
        if ((int)$amount < 0 && $abs === true) {
            if ($user_capital[$type] < abs($amount)) {
                throw new Exception(Lang::get("Deficiency of capital"), 20003);
            }
        }

        $this->update(['amount' => $user_capital[$type] + $amount], ['user_id' => $user_id, 'types' => $type]);
        
        //现金流水补充
        $logs = [
            'user_id' => $user_id, 
            'amount'  => $amount, 
            'types'   => $type, 
            'remark'  => $option['remark'],
            'options' => $option
        ];

        $this->createCapitalLogs($logs);
        //资金变动后后置操作
        Hook::exec('app\\common\\behavior\\Capital','afterCapitalOperation', $logs); 
    }
    //流水,写入日志
    private function createCapitalLogs($capital_info)
    {
        try {
            $user_info = Loader::model('common/Users')->getUserInfo(['id' => $capital_info['user_id']]);
            $base_info = [
                'branch_id'   => $user_info->camp->branch_id,//$user_info->branch_id,//$branch_id,
                'branch_name' => $user_info->camp->branch_name,
                'camp_id'     => $user_info->camp_id,
                'camp_name'   => $user_info->camp->getData('name'),
                'user_mobile' => $user_info->mobile,
                'pay_channel' => Lang::get($capital_info['types'])
            ];
            Loader::model('CapitalDetails')->create(array_merge($base_info, $capital_info), true);
        } catch (\Exception $e) {
            return false;
        }
        return true;
    }
}
